package com.jhy.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.lock.annotation.Lock4j;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jhy.core.domain.LoginUser;
import com.jhy.core.domain.R;
import com.jhy.core.enums.DeviceType;
import com.jhy.core.helper.LoginHelper;

import com.jhy.core.utils.Check;
import com.jhy.core.utils.redis.RedisUtils;
import com.jhy.system.domain.TOrder;
import com.jhy.system.domain.TUser;
import com.jhy.system.mapper.TOrderMapper;
import com.jhy.system.mapper.TUserMapper;
import com.jhy.ws.constants.WebSocketConstant;
import com.jhy.ws.domain.bo.WsMsgRecordBo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;

import javax.validation.Valid;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CountDownLatch;

@RequiredArgsConstructor
@RestController
public class TestController {


    private final TOrderMapper orderMapper;
    private final TUserMapper userMapper;

    @GetMapping("/login")
    public R<String> list() {
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(123L);
        loginUser.setUserType("sys_user");
        LoginHelper.loginByDevice(loginUser, DeviceType.PC);
//        String device = DeviceType.PC.getDevice();
//        StpUtil.login(loginUser.getLoginId(), device);
//        StpUtil.getTokenSession().set("loginUser", loginUser);
        return R.ok("ok",StpUtil.getTokenValue());
    }


    @Lock4j(keys = "#str")
    @GetMapping("/testPublic")
    public String test(String str) throws InterruptedException {
//        List<TUser> users = new ArrayList<>();
//        for (int i = 0; i < 5; i++) {
//            TUser user = new TUser();
//            user.setId((long) i);
//            user.setAge(i);
//            user.setCreateTime(new Date());
//            user.setName("test" + i);
//            users.add(user);
//        }
//        userMapper.insertBatch(users);
//        WsMsgRecordBo recordBo = new WsMsgRecordBo();
//        recordBo.setFromUser("eeee");
//        RedisUtils.publish(WebSocketConstant.ONLINE_STATUS_QUEUE,recordBo,msg->{
//            System.out.println("发送成功");
//        });

        System.out.println(Thread.currentThread().getName());
        Thread.sleep(10000);
        return "test";
    }

    @GetMapping("/select")
    public R<List<TUser>> select(String name) {
        LambdaQueryWrapper<TUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(Check.isNoEmpty(name),TUser::getName, name);
        return R.ok(userMapper.selectList(wrapper));
    }

    @GetMapping(value = "/streamTestPublic", produces = MediaType.APPLICATION_NDJSON_VALUE)
    public Flux<String> streamTestPublic() throws InterruptedException {
        return WebClient.create().get()
                .uri("http://127.0.0.1:8128/stream-ssePublic")
                .accept(MediaType.APPLICATION_NDJSON)
                .retrieve()
                .bodyToFlux(String.class)
                // 添加必要的转换和处理
                .map(data -> "代理数据: " + data)
                // 添加错误处理
                .onErrorResume(e -> {
                    System.err.println("代理请求错误: " + e.getMessage());
                    return Flux.just("{\"error\":\"代理请求失败\"}");
                });
    }

    @GetMapping(value = "/stream-ssePublic", produces = MediaType.APPLICATION_NDJSON_VALUE)
    public Flux<String> streamDataSSE() {
        return getStreamingDataFromExternalService();
    }

    private Flux<String> getStreamingDataFromExternalService() {
//        return Flux.interval(Duration.ofMillis(500)) // 每500毫秒产生一个数据
//                .map(i -> "Data " + i);
        return Flux.interval(Duration.ofSeconds(1))
                .takeUntil(i -> i == 10)
                .map(i -> "{\"id\":" + i + ", \"value\":\"data" + i + "\"}\n");
    }


    //  数据类
    public static class MyData {
        private String value;

        public MyData(String value) {
            this.value = value;
        }


        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }


    }
}
